package com.jintu.portal.repository.mongo;

import com.mongodb.client.MongoCollection;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import javax.annotation.Resource;

/**
 * @author very
 */
@Slf4j
public abstract class AbstractMongoDao<T> {

    @Resource
    protected MongoTemplate mongoTemplate;

    public void save(T val){
        if(val == null){
            return;
        }
        mongoTemplate.save(val);
    }

    public void save(Object val, String collection){
        mongoTemplate.save(val, collection);
    }

    public T queryById(String id, Class<T> cls){
        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), cls);
    }

    public T queryByColumn(String column, String value, Class<T> cls){
        return mongoTemplate.findOne(new Query(Criteria.where(column).is(value)), cls);
    }

    public void deleteById(String id, Class<T> cls) {
        mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), cls);
    }

    public void update(String whereColumn, Object whereValue, String updateColumn, Object updateValue, String collection){
        Query query = new Query();
        query.addCriteria(Criteria.where(whereColumn).is(whereValue));
        Update update = Update.update(updateColumn, updateValue);
        mongoTemplate.upsert(query, update, collection);
    }

    public MongoCollection<Document> getCollection(String collectionName) {
        if (StringUtils.isBlank(collectionName)) {
            return null;
        }
        return mongoTemplate.getCollection(collectionName);
    }

}
